package com.douwong.student.socket;

import android.content.Context;
import android.os.SystemClock;
import android.util.Log;

import com.douwong.student.activity.ClassTestActivity;
import com.douwong.student.activity.GroupTalkActivity;
import com.douwong.student.activity.HandWriteAllClassAnswerActivity;
import com.douwong.student.activity.HandWriteExchangeActivity;
import com.douwong.student.activity.HandWriteRadomAnswerActivity;
import com.douwong.student.activity.HandWriteResponderActivity;
import com.douwong.student.activity.LockActivity;
import com.douwong.student.activity.LoginClassActivity;
import com.douwong.student.activity.QuestionAnswerActivity;
import com.douwong.student.activity.ResponderActivity;
import com.douwong.student.activity.TestInfoActivity;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.contant.Config;
import com.douwong.student.enums.E_Code;
import com.douwong.student.enums.E_CommandType;
import com.douwong.student.enums.E_Destination;
import com.douwong.student.factory.ThreadFactory;
import com.douwong.student.model.DiscussSendData;
import com.douwong.student.model.JoinClassInfo;
import com.douwong.student.model.LoginTeacherServiceInfo;
import com.douwong.student.model.QaTopic;
import com.douwong.student.model.StudentGetTeacherInfo;
import com.douwong.student.model.StudnetStateInfo;
import com.douwong.student.model.TcpPacket;
import com.douwong.student.model.TeacherInfo;
import com.douwong.student.model.TeacherOnline;
import com.douwong.student.synscreen.SynScreenActivity;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.FtpUtils;
import com.douwong.student.utils.JsonUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.utils.UIUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.douwong.student.contant.Config.HEART_INTERVAL;
import static com.douwong.student.contant.Config.HEART_TIMEOUT;
import static com.douwong.student.utils.UIUtils.sendBroadcast;

/**
 * @autor yichao
 * @time 2017/3/3013:46
 * @des 处理长连接消息
 */
public class TcpMessageHandle {
    private Context mContext;
    private static TcpMessageHandle mTcpMessageHandle;
    private ArrayList<TeacherOnline> mTeacherOnlineList;
    private static final String TAG = "TcpMessageHandle";
    private String mQuestionAnswerGuid;//问答互动guiid
    private String mQuestionAnswerimageUrl="";//问答互动图片地址
    private String mFileUuid;//下载文件uuid
    private String mAnnex; //小组讨论图片地址
    private String mDiscussGuid ;//下载文件uuid;
    private Timer mCheckHeartTimer;
    private byte[] heartData=  new byte[]{1};


    private TcpMessageHandle(Context context) {
        this.mContext = context;
    }
    public static TcpMessageHandle createInstance(Context context) {
        if (mTcpMessageHandle == null) {
            synchronized (TcpMessageHandle.class) {
                if (mTcpMessageHandle == null) {
                    mTcpMessageHandle = new TcpMessageHandle(context);
                }
            }
        }
        return mTcpMessageHandle;
    }

    /**
     * 分发消息
     *
     * @param pack
     * @param commandType
     */
    public void dispatchMessager(TcpPacket pack, E_CommandType commandType) {
        // LongConnSubject.getInstance().sendMsg(pack,commandType);
        switch (commandType) {
            case studentGetTeacher:
                //学生获取老师
                handlerStudentGetTeacher(pack);
                break;
            case serverLoginStudent:
                //学生加入课堂
                handlerServerLoginStudent(pack);
                break;
            case closeConnent:
                //老师断开连接
                handlerTecherCloseConnent(pack);
                break;
            case testSend:
                //课堂测试发布
                handlerTestSend(pack);
                break;
            case testCollect:
                //收取课堂测试
                sendBroadcast(mContext, Config.TEST_COLLECT);
                break;

            case testStatistics:
                //老师推送学生
                String serialize = JsonUtils.serialize(pack.data);
                TestInfoActivity.startActivity(mContext, serialize);
                break;
            case sendStudentState:
                //学生端的状态
                StudnetStateInfo deserializw = JsonUtils.deserializw(pack.getData(), StudnetStateInfo.class);
                if (deserializw != null) {
                    handlerStudentState(deserializw);
                }
                break;
            case qaSendSubject:
                //互动问答
                if (!QuestionAnswerActivity.isShown){
                    QuestionAnswerActivity.startActivity(mContext);
                    SystemClock.sleep(1000);
                }
                //
                mQuestionAnswerGuid = pack.getGuid().toString();
               QaTopic qaTopic = JsonUtils.deserializw(pack.getData(), QaTopic.class);
                if (qaTopic!=null){
                    mQuestionAnswerimageUrl = qaTopic.getImageUrl();
                    if (mQuestionAnswerimageUrl != null && mQuestionAnswerimageUrl.length() != 0) {
                        //下载图片.图片还未上传成功
                       // downFilePic(imageUrl);
                    }
                }
                String json = JsonUtils.serialize(pack.getData());
                if (json!=null){
                    sendBroadcast(mContext,Config.QUESTION_ANSWER_SEND,json);
                }
                break;

            case qaPublicAnswer:
                //公布互动答案
                String publicaAnswerJson = JsonUtils.serialize(pack.getData());
                sendBroadcast(mContext,Config.QUESTION_ANSWER_PUBLICANSWER,publicaAnswerJson);
                break;
            case qaEnd:
                //结束问答互动
                sendBroadcast(mContext,Config.FINISH_QUESTION_ANSWER);
                break;
            case finishStatistics:
                //结束推送答案
                sendBroadcast(mContext,Config.FINISH_STATISTICS);
                break;
            case discussSend:
                //小组讨论
                if (!GroupTalkActivity.isShow){
                    GroupTalkActivity.startActivity(mContext);
                    SystemClock.sleep(1000);
                }
                mDiscussGuid = pack.getGuid().toString();
                sendBroadcast(mContext,Config.GROUP_DISCUSSION_SEND,JsonUtils.serialize(pack.getData()));
                //下载附件

                DiscussSendData deserializw1 = JsonUtils.parseObject(pack.getData(), DiscussSendData.class);
                mAnnex = deserializw1.getAnnex();
                if (mAnnex !=null&& mAnnex.length()!=0){
                 //   downFilePic(mAnnex);
                }
                break;
            case discussConfirm:
                //确定小组长
                sendBroadcast(mContext,Config.GROUP_DISCUSSION_CONFIRM_LEADER,JsonUtils.serialize(pack.getData()));
                break;
            case discussEnd:
                //结束小组讨论
                sendBroadcast(mContext,Config.FINSH_DISCUSSEND);
                break;
            case uploadSuccess:
                //问答互动文件、小组讨论文件
                mFileUuid = pack.getData().toString();
                if (mFileUuid.equalsIgnoreCase(mQuestionAnswerGuid) &&mQuestionAnswerimageUrl!=null &&!mQuestionAnswerimageUrl.equals("")){
                    downFilePic(mQuestionAnswerimageUrl);
                }else if (mFileUuid.equalsIgnoreCase(mDiscussGuid)&&mAnnex!=null &&!mAnnex.equals("")){
                    downFilePic(mAnnex);
                }

                break;
            case hwSend:
                //发送手写互动
                UIUtils.sendBroadcast(mContext,Config.HANDER_WRITE_EXCHANGE_FINSH);
                SystemClock.sleep(200);
                HandWriteExchangeActivity.startActivity(mContext,pack.getData().toString());
                break;
            case hwchange:
                //改变手写互动的状态
                String data=pack.getData().toString();
                int code=Integer.parseInt(data);
                handlerHwChange( code);

                break;
            case hwsubmit:
                //提交手写互动
                UIUtils.sendBroadcast(mContext,Config.HANDER_WRITE_EXCHANGE_SUBMIT);
                break;
            case answer:
                //发布抢答问题
                ResponderActivity.startActivity(mContext);

                break;


            case answerCnfirm:
                //发布抢答题

             //   HandWriteResponderActivity
                String respondfilePath = pack.getData().toString();
                if (respondfilePath!=null && respondfilePath.length()!=0){
                    //开启随机作答

                    HandWriteResponderActivity.startActivity(mContext,respondfilePath);


                }
                break;
            case answerRandom:
                //随机作答
                String filePath = pack.getData().toString();
                if (filePath!=null && filePath.length()!=0){
                    //开启随机作答
                    HandWriteRadomAnswerActivity.startActivity(mContext,filePath);

                }


                break;
            case answerClass:
                //全班作答
                String filePathAllClass = pack.getData().toString();
                if (filePathAllClass!=null && filePathAllClass.length()!=0){
                    //开启随机作答
                    HandWriteAllClassAnswerActivity.startActivity(mContext,filePathAllClass);

                }






                break;


        }
    }

    /**
     * 处理手写互动编辑、不可编辑、提交
     * @param code
     */
    private void handlerHwChange(int code) {
        switch (code) {
            case 1:
            //可编辑
                sendBroadcast(mContext,Config.HANDER_WRITE_EXCHANGE_CHANGE);
                break;
            case 2:
                //不可编辑
                sendBroadcast(mContext,Config.HANDER_WRITE_EXCHANGE_UNCHANGE);
                break;
            case 3:
                //提交答案
                sendBroadcast(mContext,Config.HANDER_WRITE_EXCHANGE_SUBMIT);
                break;
            case 4:
                UIUtils.sendBroadcast(mContext,Config.HANDER_WRITE_EXCHANGE_FINSH);

                break;

        }


    }

    /**
     * 下载ftp图片
     * @param imageUrl
     */
    private void downFilePic(final String imageUrl) {
        ThreadFactory.getDownLoadPool().execute(new Runnable() {
            @Override
            public void run() {
                int index = imageUrl.lastIndexOf("/");
                String imageName = imageUrl.substring(index + 1, imageUrl.length());
                FtpUtils ftp = new FtpUtils();
                try {
                    ftp.downloadSingleFile(imageUrl, FileUtils.IMAGE_DIR, imageName, new FtpUtils.DownLoadProgressListener() {
                        @Override
                        public void onDownLoadProgress(String currentStep, long downProcess, File file) {
                            switch (currentStep) {
                                case Config.FTP_DOWN_FAIL:
                                    ToastUtils.makeText( UIUtils.getContext(),"图片下载失败");
                                    if (imageUrl.equalsIgnoreCase(mAnnex)){

                                    sendBroadcast(mContext,Config.GROUP_DISCUSSION_FILE_DOWN_FAILURE);
                                    }else if (imageUrl.equalsIgnoreCase(mQuestionAnswerimageUrl)){
                                        sendBroadcast(mContext,Config.QUESTION_ANSWER_FILE_DOWN_FAILURE);
                                    }

                                    break;

                                case Config.FTP_DOWN_SUCCESS:
                                    if (imageUrl.equalsIgnoreCase(mAnnex)){
                                        sendBroadcast(mContext,Config.GROUP_DISCUSSION_FILE_DOWN_SUCCESS,file.getAbsolutePath());
                                    }else if (imageUrl.equalsIgnoreCase(mQuestionAnswerimageUrl)){
                                        sendBroadcast(mContext,Config.QUESTION_ANSWER_FILE_DOWN_SUCCESS,file.getAbsolutePath());
                                    }
                                    break;
                                case Config.FTP_CONNECT_FAIL:
                                case Config.FTP_FILE_NOTEXISTS:

                                    if (imageUrl.equalsIgnoreCase(mAnnex)){

                                        sendBroadcast(mContext,Config.GROUP_DISCUSSION_FILE_DOWN_FAILURE);
                                    }else if (imageUrl.equalsIgnoreCase(mQuestionAnswerimageUrl)){
                                        sendBroadcast(mContext,Config.QUESTION_ANSWER_FILE_DOWN_FAILURE);
                                    }
                                    ToastUtils.makeText(mContext,currentStep);
                                    break;
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.makeText( UIUtils.getContext(),"图片下载失败");
                    if (imageUrl.equalsIgnoreCase(mAnnex)){

                        sendBroadcast(mContext,Config.GROUP_DISCUSSION_FILE_DOWN_FAILURE);
                    }else if (imageUrl.equalsIgnoreCase(mQuestionAnswerimageUrl)){
                        sendBroadcast(mContext,Config.QUESTION_ANSWER_FILE_DOWN_FAILURE);
                    }

                }
            }
        });

    }

    /**
     * 处理学生状态
     *
     */
    private void handlerStudentState(  StudnetStateInfo studnetStateInfo) {


        switch (studnetStateInfo.getState()) {
            case lock:
                if (!LockActivity.isShow){
                    LockActivity.startActivity(mContext);
                }
                break;
            case unlocked:
                sendBroadcast(mContext,Config.NO_LOCKSREEN);
                break;
            case sync:
                SynScreenActivity.startActivity(mContext);
                break;
            case unsync:
                sendBroadcast(mContext,CommonConfig.SYNSCREEN_CLOSE);
                break;

        }

     /*   if (studnetStateInfo.getLocked()==E_StudentState.lock){
            if (!LockActivity.isShow){
                LockActivity.startActivity(mContext);
            }

        }else if (studnetStateInfo.getLocked()==E_StudentState.unlocked){
            sendBroadcast(mContext,Config.NO_LOCKSREEN);
        }

        if (studnetStateInfo.getSync()==E_StudentState.sync){
            //同步
            SynScreenActivity.startActivity(mContext);
        }else if (studnetStateInfo.getSync()==E_StudentState.unsync){
            //关闭同步
            sendBroadcast(mContext,CommonConfig.SYNSCREEN_CLOSE);
        }*/

        String ip = studnetStateInfo.getIp();
        short port = studnetStateInfo.getPort();

        if (ip!=null &&!ip.equals("") &&port!=0){
            CommonConfig.UDP_BROADCAST_IP=ip;
            CommonConfig.UDP_BROADCAST_PORT=port;
        }


  /*      switch (deserializw) {
            case lock:
                if (!LockActivity.isShow){
                    LockActivity.startActivity(mContext);
                }
                break;


           *//* case noState:
                sendBroadcast(mContext,Config.NO_LOCKSREEN);
                sendBroadcast(mContext,CommonConfig.SYNSCREEN_CLOSE);
                break;*//*
            case sync:
                String[] split = value.split(":");
                CommonConfig.UDP_BROADCAST_IP=split[0];
                CommonConfig.UDP_BROADCAST_PORT=Integer.parseInt(split[1]);
                LogUtils.i(TAG,"组播地址 ："+value);

                SynScreenActivity.startActivity(mContext);

                break;


        }*/

    }

    /**
     * 处理测试题发布
     *
     * @param pack
     */
    private void handlerTestSend(TcpPacket pack) {
        if (pack.getCode() == E_Code.ok) {
        /* UIUtils.sendBroadcast(mContext,Config.CLASS_TEST_FINSH);
            SystemClock.sleep(1000);
            ClassTestActivity.startActivity(mContext);*/

            if (!ClassTestActivity.isShown) {
                ClassTestActivity.startActivity(mContext);
                SystemClock.sleep(1000);
            }
            //  ResTestProblemsInfo resTestProblemsInfo = JsonUtils.parseObject(pack.getData(), ResTestProblemsInfo.class);
            String serialize = JsonUtils.serialize(pack.getData());
            //发送测试题广播
           sendBroadcast(mContext, Config.SEND_TEST, serialize);
        }
    }

    /**
     * 老师断线
     *
     * @param pack
     */
    private void handlerTecherCloseConnent(TcpPacket pack) {
        BaseApplication.isTeaching = false;
        BaseApplication.isCancelConn=true;
        //老师下线
        stopCheckHeart();
        sendBroadcast(mContext,Config.TEACHER_LEAVE_CLASS);
        LTPServer.createInstance(mContext).endWork();
        sendBroadcast(mContext,Config.LOGIN_CLASS_FAILURE);
        BaseApplication.sTeacherOnline=null;
        if (pack.getCode() == E_Code.ok) {
            TeacherInfo teacherInfo = JsonUtils.parseObject(pack.getData(), TeacherInfo.class);
            if (teacherInfo != null) {
                ToastUtils.makeText(mContext, teacherInfo.teacherRemark + "离开课堂");
            }
        }
    }

    /**
     * 处理学生加入课堂
     *
     * @param pack
     */
    private void handlerServerLoginStudent(TcpPacket pack) {

        if (pack.getCode() == E_Code.ok) {
            switch (pack.getState()) {
                case loginSuccess:
                    loginClassSuccessState();
                    JoinClassInfo joinClassInfo = JsonUtils.parseObject(pack.getData(), JoinClassInfo.class);
                    if (joinClassInfo != null) {
                        BaseApplication.sFtpInfo = joinClassInfo.ftp;
                    }
                    //加入检测机制
                    BaseApplication.currentHeartTime=System.currentTimeMillis();
                    checkHeart();

                    break;
                case loginFailed:
                    ToastUtils.makeText(mContext, "加入课堂失败");
                    loginClassFailState();
                    break;
                case kickOut:
                    loginClassFailState();
                    ToastUtils.makeText(mContext, "该账好在另一端登录,强制断线");
                    break;
            }

        } else {
            loginClassFailState();

        }

    }

    /**
     * 检测心跳初始化
     */
    private void checkHeart() {
        if (mCheckHeartTimer==null){
        mCheckHeartTimer = new Timer();
        }

           //长连接没断线
           mCheckHeartTimer.schedule(new TimerTask() {
               @Override
               public void run() {
                   //发送心跳
                   if ( System.currentTimeMillis()-BaseApplication.currentHeartTime>HEART_TIMEOUT){
                       //认为长连接断线
                       stopCheckHeart();
                       LTPServer.createInstance(mContext).endWork();
                   }else {
                       //发送心跳
                       LTPServer.createInstance(mContext).sendHeartMsg(heartData);
                       Log.i(TAG, "发送 心跳消息 ： " + 1);

                   }



               }
           },1000,HEART_INTERVAL);



    }

    /**
     * 停止检测心跳
     */
    public void stopCheckHeart(){
        if (mCheckHeartTimer!=null){
            mCheckHeartTimer.cancel();
            mCheckHeartTimer=null;
        }

    }

    /**
     * 加入课堂失败
     */
    public void loginClassFailState() {
        BaseApplication.isLoginClass = false;
        BaseApplication.temTeacherOnline = null;
        BaseApplication.isTeaching = false;
        BaseApplication.sTeacherOnline = null;

        sendBroadcast(mContext, Config.LOGIN_CLASS_FAILURE);
    }

    /**
     * 加入课堂成功
     */
    public void loginClassSuccessState() {
        if (BaseApplication.temTeacherOnline != null) {
            BaseApplication.sTeacherOnline = BaseApplication.temTeacherOnline;
            BaseApplication.temTeacherOnline = null;
        }
        BaseApplication.isLoginClass = true;
        BaseApplication.isCloseConn = false;
        BaseApplication.isCancelConn = false;
        BaseApplication.isTeaching = true;
        sendBroadcast(mContext, Config.LOGIN_CLASS_SUCESS);
    }

    /**
     * 处理学生登录教师服务器
     *
     * @param tcpPacket
     */
    private void handlerStudentGetTeacher(TcpPacket tcpPacket) {
        //   LoginClassActivity.startActivity(mContext,null);

        StudentGetTeacherInfo studentGetTeacherInfo = JsonUtils.parseObject(tcpPacket.getData(), StudentGetTeacherInfo.class);

        if (studentGetTeacherInfo != null) {
            if (BaseApplication.sTeacherOnline != null) {
                LoginTeacherServiceInfo loginTeacherServiceInfo = new LoginTeacherServiceInfo();
                loginTeacherServiceInfo.studentInfo = BaseApplication.sStudentOnline;
                loginTeacherServiceInfo.teacherInfo = BaseApplication.sTeacherOnline;
                loginTeacherServiceInfo.studentAtt=BaseApplication.sStudentAtt;
                LTPServer.createInstance(mContext).sendMsg(loginTeacherServiceInfo, E_CommandType.serverLoginStudent, E_Destination.server, new int[]{0});
                return;
            }
            List<TeacherOnline> localOnlineTeachers = studentGetTeacherInfo.getLocalOnlineTeacher();
            List<TeacherOnline> remoteOnlineTeachers = studentGetTeacherInfo.getRemoteOnlineTeacher();

            if ((localOnlineTeachers != null && localOnlineTeachers.size() > 0) || (remoteOnlineTeachers != null && remoteOnlineTeachers.size() > 0)) {
                mTeacherOnlineList = new ArrayList<>();
                mTeacherOnlineList.clear();
                if ((localOnlineTeachers != null && localOnlineTeachers.size() > 0)) {
                    //本地老师
                    for (TeacherOnline localOnlineTeacher : localOnlineTeachers) {
                        localOnlineTeacher.isLocal = true;
                        mTeacherOnlineList.add(localOnlineTeacher);
                    }
                }
                if (remoteOnlineTeachers != null && remoteOnlineTeachers.size() > 0) {
                    //远程老师
                    for (TeacherOnline remoteOnlineTeacher : remoteOnlineTeachers) {
                        remoteOnlineTeacher.isLocal = false;
                        mTeacherOnlineList.add(remoteOnlineTeacher);
                    }
                }
                String serialize = JsonUtils.serialize(mTeacherOnlineList);
                //  LoginClassActivity.startActivity(mContext,mTeacherOnlineList);
                LoginClassActivity.startActivity(mContext, serialize);

                //  TeacherInfoPopuwindow mTeacherInfoPopuwindow = new TeacherInfoPopuwindow(this, mTeacherOnlineList);
                //                mTeacherInfoPopuwindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
            } else {
                sendBroadcast(mContext,Config.CLOSE_LOGINING_POPUWINDOW);
                ToastUtils.makeText(mContext, "老师不在线");
                BaseApplication.isCloseConn = true;
                LTPServer.createInstance(mContext).endWork();

            }
        } else {
            sendBroadcast(mContext,Config.CLOSE_LOGINING_POPUWINDOW);
            ToastUtils.makeText(mContext, "老师不在线");
            BaseApplication.isCloseConn = true;
            LTPServer.createInstance(mContext).endWork();

        }


    }
}
